<template>
  <view class="hydropower-details">
    <view class="return-box" @click="goBack">
      <up-icon name="arrow-left"></up-icon>
    </view>
    <view class="tabs">
      <up-tabs
        @change="onCurrentTab"
        :list="orderTabDict"
        :lineWidth="`25% - ${rpx2px(22)}px`"
        :line-height="rpx2px(11)"
        :activeStyle="{
          color: '#303133',
          fontWeight: 'bold',
          transform: 'scale(1.05)',
        }"
      />
    </view>
    <view class="payment-box" v-if="orderCall == 0">
      <view class="payment-information">
        <h4 class="payment-title">消息通知</h4>
        <view class="payment-content">
          <view class="payment-icon"></view>
          <!-- #ifndef MP-WEIXIN -->
          <up-notice-bar
            bgColor="transparent"
            :text="text"
            :fontSize="14"
            speed="50"
            icon=""
          >
          </up-notice-bar>
          <!--  #endif -->
          <!-- #ifndef APP-PLUS || H5  -->
          <up-notice-bar
            bgColor="transparent"
            :text="text"
            :fontSize="px2Rpx(14)"
            speed="50"
            icon=""
          >
          </up-notice-bar>
          <!-- #endif  -->
        </view>
      </view>
      <view class="payment-form">
        <view class="coins-box">
          <view class="coins">
            <view class="coins-img"></view>
            <view class="coins-text">
              余额¥{{ balance }} 元
              <text v-if="balance <= 10" class="coins-prompt"> 余额低 </text>
            </view>
          </view>
        </view>
        <up-cell-group :border="false">
          <up-cell title="缴费户名" :value="room"></up-cell>
          <up-cell title="表号" :value="identifier"></up-cell>
          <up-cell
            v-if="titleType == '电费'"
            title="电费标准"
            :value="standard"
          ></up-cell>
          <up-cell
            v-if="titleType == '水费'"
            title="水费标准"
            :value="standard"
          ></up-cell>
          <up-cell title="请输入金额">
            <template #label>
              <input
                v-model="amountVal"
                placeholder="最低应缴0.01元"
                :cursor-spacing="50"
                maxlength="7"
                type="numder"
                inputmode="none"
                style="margin-top: 20rpx"
                @focus="keyboardShow = true"
              />
            </template>
          </up-cell>
        </up-cell-group>
        <view class="item-box">
          <view
            class="u-page__tag-item"
            v-for="(item, index) in radios"
            :key="index"
          >
            <up-tag
              :text="item.value"
              :plain="!item.checked"
              type="success"
              :name="item.name"
              @click="radioClick"
            >
            </up-tag>
          </view>
        </view>
      </view>
    </view>

    <view class="payment-records" v-if="orderCall == 1">
      <none-data v-if="payList.length === 0" />
      <recordsCard
        v-for="(item, index) in payList"
        :key="index"
        :type="titleType"
        :identifier="item.accountNumber"
        :balance="item.totalDosage"
        :time="item.weekInterval"
      />
      <view class="tail" v-if="payList.length !== 0">
        {{ tailText }}
      </view>
    </view>
    <!-- <my-tab
      :tabBars="orderTabDict"
      :current="orderCall"
      @on-current-tab="onCurrentTab"
      @on-loadmore-tab="onLoadmoreTab"
      className="none"
    >
      
    </my-tab> -->
    <keyboard
      :show="keyboardShow"
      :dark="false"
      :isDecimal="true"
      confirmText="确定"
      @change="getNumber"
      @confirm="handlerPay"
    ></keyboard>
    <view class="room-btn" style="z-index: 9" v-if="orderCall == 0">
      <button class="btn" form-type="submit" @tap="rechargeClick">
        立即充值
      </button>
    </view>
  </view>
</template>

<script setup>
import keyboard from "@/package_property/pages/components/keyboard.vue";
import {
  onLoad,
  onPullDownRefresh,
  onReachBottom,
  onShow,
} from "@dcloudio/uni-app";
import recordsCard from "@/package_property/pages/components/records-card/x.vue";
import {
  getWaterElectricityListApi,
  getWaterElectricityLogDayApi,
  waterElectricityRechargeApi,
} from "@/package_property/pages/api/life-services.js";
import { getCurrentPagesTotal, rpx2px, px2Rpx } from "@/utils/utils";
import { ref, reactive } from "vue";
import { customNav } from "@/utils/customNav";
// tab菜单字典
const tailText = ref("");
const payId = ref(null);
const titleType = ref(null);
const orderTabDict = ref(null);
const orderCall = ref(0);
const amountVal = ref();
const keyboardShow = ref(false);
const balance = ref("0.00");
const room = ref("");
const identifier = ref("");
const standard = ref("");
const page = ref(1);
const size = ref(10);
const total = ref(0);
const payList = ref([]);
const radios = reactive([
  { checked: true, value: "50元", name: 50 },
  { checked: false, value: "100元", name: 100 },
  { checked: false, value: "150元", name: 150 },
]);
const radiosNun = ref(50);
const text = ref("");
function radioClick(name) {
  radios.forEach((item) => {
    item.checked = item.name === name;
  });
  console.log("name", name);
  radiosNun.value = name;
}
function onCurrentTab(e) {
  console.log(e);
  orderCall.value = e.index;
  if (orderCall.value == 1) {
    getWaterElectricityLog();
  }
}
// function onLoadmoreTab() {}
function goBack() {
  uni.navigateBack({
    delta: 1, // 默认值是1，表示返回的页面层数
  });
}
// function handleFocus() {
//   console.log("sssss");
// }
// function handleBlur() {
//   console.log("zzzzzzz");
// }
const getNumber = (e) => {
  console.log("e", e);
  amountVal.value = e;
};

//收起键盘
const handlerPay = async () => {
  keyboardShow.value = false;
};
const rechargeClick = async () => {
  let option = {
    id: payId.value,
    accountNumber: room.value,
    money:
      amountVal.value !== "" && amountVal.value !== undefined
        ? amountVal.value
        : radiosNun.value,
    rechargeType: titleType.value == "水费" ? "3" : "2",
    // #ifdef MP-WEIXIN
    payType: "0",
    // #endif
    // #ifdef APP-PLUS || H5
    payType: "1",
    // #endif
  };
  const res = await waterElectricityRechargeApi(option);
  const { code, data } = res || {};
  if (code == 200) {
    // #ifdef MP-WEIXIN
    toPay(data);
    // #endif
    // #ifdef APP-PLUS || H5
    weChatAppPay(data);
    // #endif
  }
};
async function getWaterElectricityLog() {
  const option = {
    accountNumber: room.value,
    page: page.value,
    size: size.value,
    feeDeduction: titleType.value == "水费" ? "1" : "2",
  };
  const res = await getWaterElectricityLogDayApi(option);
  const { code, data } = res || {};
  if (code == 200) {
    total.value = data.total;
    payList.value = payList.value.concat(data.records) ;
    if (payList.value.length !== data.total) {
      tailText.value = "下滑加载更多";
    } else {
      tailText.value = "没有更多内容";
    }
  }
}
/**
 * 唤起微信支付
 * @param payData
 */
const toPay = (payData) => {
  uni.requestPayment({
    provider: "wxpay",
    timeStamp: payData.timeStamp,
    nonceStr: payData.nonceStr,
    package: payData.prepayId,
    signType: payData.signType,
    paySign: payData.paySign,
    success: function (res) {
      console.log("success:" + JSON.stringify(res));
      uni.showToast({
        title: "支付成功",
        duration: 2000,
        success: () => {
          amountVal.value = "";
          getWaterElectricityList();
        },
      });
    },
    fail: function (err) {
      userCancelPayApi(orderDetail.value.reserveId).then((res) => {
        console.log("success" + JSON.stringify(res.data));
      });
      console.log("fail:" + JSON.stringify(err));
    },
  });
};
// 微信APP支付
const weChatAppPay = (payData) => {
  let params = {
    partnerId: payData.partnerId, //商户号
    prepayId: payData.prepayId, //预支付交易会话ID
    nonceStr: payData.nonceStr, //随机字符串
    timeStamp: payData.timeStamp, //时间戳
    sign: payData.paySign, //签名
  };
  window.mobile.jsCallPayWx(JSON.stringify(params));
  setTimeout(() => {
    getWaterElectricityList();
  }, 1500);
  // customNav("/package_kuafu_apartment/pages/home/pages/life-services/hydropower")
};
async function getWaterElectricityList() {
  let option = {
    accountNumber: room.value,
    page: 1,
    queryType: titleType.value == "水费" ? "1" : "2",
    size: 10,
  };
  const res = await getWaterElectricityListApi(option);
  console.log(res);
  const { code, data } = res || {};
  if (code == 200) {
    if (data.records.length !== 0) {
      payId.value = data.records[0].id;
      balance.value = data.records[0].waterAccount;
      identifier.value =
        titleType.value == "水费"
          ? data.records[0].imeiWater
          : data.records[0].imeiLock;
      standard.value =
        titleType.value == "水费" ? data.records[0].waterChargeStandard : "";
    }
  }
}
onLoad((option) => {
  const options = JSON.parse(option.data);
  console.log(options);
  titleType.value = options.type;
  room.value = options.room;
  getWaterElectricityList();
  text.value = `尊敬的用户，${titleType.value}为负数时且在规定的时间内未缴纳${
    titleType.value
  }，将会限制您的${titleType.value == "电表" ? "用电" : "用水"}需求。`;
  if (titleType.value == "水表") {
    orderTabDict.value = [
      {
        name: "水费缴纳",
        id: 0,
      },
      {
        name: "用量记录",
        id: 1,
      },
    ];
  } else {
    orderTabDict.value = [
      {
        name: "电费缴纳",
        id: 0,
      },
      {
        name: "用量记录",
        id: 1,
      },
    ];
  }
});
onPullDownRefresh(() => {
  getWaterElectricityList();
  uni.stopPullDownRefresh();
});
onReachBottom(() => {
  page.value++;
  getWaterElectricityLog();
});
</script>

<style lang="less" scoped>
@import url(./style/hydropower-details.less);
</style>